import express from "express"
import path from "path"
import fs from "fs"
import uuid from "node-uuid"
let PublicUrl = path.join(__dirname, "./public")
let app = express()
app.listen(3000, () => {
    console.log("服务器打开");
})
//获取 post请求参数
app.use(
    express.json()
)
app.use(
    express.urlencoded()
)
//登录拦截
app.get("/hom.html", (req, res, next) => {
    let arr = JSON.parse(fs.readFileSync(path.join(__dirname, "./public/cook.json")))
    let str = req.get("Cookie") || ""
    let brr = str.split("; ")
    let obj = {}
    brr.forEach(item => {
        obj[item.slice(0, item.indexOf("="))] = item.slice(item.indexOf("=") + 1)
    });
    let cook = obj["cook"]
    let is = arr.find(item => {
        return item === cook
    })
    if (is) {
        next()
    } else {
        res.redirect("./login.html")
    }
})


//访问静态资源
app.use(
    express.static(PublicUrl)
)
//get请求
app.get("/login", (req, res, next) => {
    let {
        user,
        pass
    } = req.query
    //登录
    let arr = JSON.parse(fs.readFileSync(path.join(__dirname, "./public/user.json")))
    let is = arr.find(item => {
        return item.user === user
    })
    if (is) {
        if (is.pass === pass) {

            //uuid
            let str = uuid.v1()
            let brr = JSON.parse(fs.readFileSync(path.join(__dirname, "./public/cook.json")))
            brr.push(str)
            fs.writeFileSync(path.join(__dirname, "./public/cook.json"), JSON.stringify(brr), "utf-8")
            res.cookie("cook", str)
            res.send("001")
        } else {
            res.send("002")
        }
    } else {
        res.send("003")
    }

})

app.post("/zhu", (req, res, next) => {
    console.log(req.body);
    // console.log(req);


})